#pragma once
// hpp 为后缀的文件，就是在

#include <iostream>
#include <unistd.h>
#include <cstring> //C++版本的string.h
#include <cerrno>  //C++版本的errno.h
#include <sys/wait.h>
#include <sys/types.h>
#include <string>
#include <vector>
#include <ctime>
#include <cstdlib>

#define TaskNum 3

typedef void(*task_t)(); // 将void(*)()这一类型命名为 task_t

void Print()
{
    std::cout << "I am a Print task" << std::endl;
}

void Download()
{
    std::cout << "I am a download task" << std::endl;
}

void Flush()
{
    std::cout << "I am a flush task" << std::endl;
}

task_t tasks[TaskNum];

void loadTask()
{
    //利用随机数，随机挑一个任务，
    srand(time(nullptr) ^ getpid() ^ 17777);
    tasks[0] = Print;
    tasks[1] = Download;
    tasks[2] = Flush;
}

void executeTask(int num)
{
    if (num < 0 || num > 2)
    {
        return;
    }
    tasks[num]();
}

int selectTask()
{
    return rand() % TaskNum;
}

void work()
{
    while (true)
    {
        int command = 0;
        int n = read(0, &command, sizeof(command));
        if (n == sizeof(int))
        {
            std::cout << "pid is: " << getpid() << "handle task" << std::endl;
            executeTask(command);
        }
        else if (n == 0)
        {
            std::cout << "subprocess : " << getpid() << "quit" << std::endl;
            break;
        }
    }
}
